package com.ruoyi.sycs.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.sycs.domain.BaQjDetail;
import com.ruoyi.sycs.domain.bo.BaQjDetailBo;
import com.ruoyi.sycs.domain.vo.BaQjDetailVo;
import com.ruoyi.sycs.mapper.BaQjDetailMapper;
import com.ruoyi.sycs.service.IBaQjDetailService;
import com.ruoyi.system.domain.vo.SysUserImportVo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 导入，或是全成功，或是全失败
 */
@Slf4j
public class BaQjDetailVoImportListener extends AnalysisEventListener<BaQjDetailVo> implements ExcelListener<BaQjDetailVo> {

    private final IBaQjDetailService baQjDetailService;
    private final BaQjDetailMapper baQjDetailMapper;

    private final Boolean isUpdateSupport;
    private final Long deptId;
    private final Long qjId;

    private final String operName;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public BaQjDetailVoImportListener(Boolean isUpdateSupport, Long deptId, Long qjId) {
        this.baQjDetailService = SpringUtil.getBean(IBaQjDetailService.class);
        this.baQjDetailMapper = SpringUtil.getBean(BaQjDetailMapper.class);
        this.isUpdateSupport = isUpdateSupport;
        this.deptId = deptId;
        this.qjId = qjId;
        this.operName = LoginHelper.getUsername();

    }

    @Override
    public ExcelResult<BaQjDetailVo> getExcelResult() {
        return new ExcelResult<BaQjDetailVo>() {
            @Override
            public List<BaQjDetailVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }
        };
    }



    @Override
    public void invoke(BaQjDetailVo voParam, AnalysisContext analysisContext) {
        BaQjDetailVo targetVo = baQjDetailMapper.selectVoOne(new LambdaQueryWrapper<BaQjDetail>()
            .eq(BaQjDetail::getDeptId, deptId)
            .eq(BaQjDetail::getQjId, qjId)
            .eq(BaQjDetail::getHh, voParam.getHh()));
        // 默认赋值
        if (ObjUtil.isNull(voParam.getHTime())) {
            voParam.setHTime(DateTime.now());
        }
        if (ObjUtil.isNull(voParam.getHPer())) {
            voParam.setHPer(operName);
        }
        voParam.setDeptId(deptId);
        voParam.setQjId(qjId);
        try {
            if (ObjUtil.isNull(targetVo)) {
                BaQjDetailBo bo = BeanUtil.toBean(voParam, BaQjDetailBo.class);
                baQjDetailService.insertByBo(bo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、盒号 ").append(voParam.getHh()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long detailId = targetVo.getDetailId();
                BaQjDetailBo bo = BeanUtil.toBean(voParam, BaQjDetailBo.class);
                bo.setDetailId(detailId);
                bo.setUpdateBy(operName);
                baQjDetailService.updateByBo(bo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、盒号 ").append(voParam.getHh()).append("更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、盒号 ").append(voParam.getHh()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、盒号 " + voParam.getHh() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
            throw new ServiceException(failureMsg.toString());
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        throw new ServiceException(exception.getMessage());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
